# -*- coding: utf-8 -*-
import requests
import xlwt
import xlrd
from bs4 import BeautifulSoup
import os
import shutil
import sys
# python2 和 python3的兼容代码
try:
    import cookielib

    print("user cookielib in python2.")
except:
    import http.cookiejar as cookielib

    print("user cookielib in python3.")

os.chdir(sys.path[0])

def mkdir(path):
    # 去除首位空格
    path = path.strip()
    # 去除尾部 \ 符号
    path = path.rstrip("\\")

    # 删除旧目录
    if os.path.exists(path):
        # os.removedirs(path) # 不能删除非空文件目录
        shutil.rmtree(path)  # 递归删除文件夹 可以删除非空文件夹

    # 创建新目录
    os.makedirs(path)
    return path

def iOSCheckString(value):

    # value = string.strip()  # 移除字符串头尾指定的字符（默认为空格或换行符）或字符序列 注意：该方法只能删除开头或是结尾的字符，不能删除中间部分的字符
    # colString = td.string.replace(u'\xa0', '') #去除空格
    # 有可能是安卓添加的，翻译过来可能会有以下特殊字符，都 要换成%@
    value = value.replace('%s', '%@')
    value = value.replace('% s', '%@')
    value = value.replace('%$s', '%@')
    value = value.replace('%1$s', '%@')
    value = value.replace('%2$s', '%@')
    value = value.replace('%3$s', '%@')
    value = value.replace('%4$s', '%@')
    value = value.replace('%5$s', '%@')
    value = value.replace('%1$ s', '%@')
    value = value.replace('%2$ s', '%@')
    value = value.replace('%3$ s', '%@')
    value = value.replace('%4$ s', '%@')
    value = value.replace('%5$ s', '%@')

    return value

def androidString(key,value):
    value = value.replace('%@', '%s')
    text = '<' + 'string name=' + '\"' + key.strip() + '\"' + '>' + value.strip() + '</string>' + '\n'
    return text

def iosString(key,value):
    value = iOSCheckString(value)
    text = '\"' + key + '\"' + ' = ' + '\"' + value + '\"' + ';\n'
    return text

def read_excel(excel):
    ExcelFile = xlrd.open_workbook(excel)
    sheet = ExcelFile.sheet_by_name('test')
    # cols = sheet.col_values(2)  # 第二列为Android key值
    cols = sheet.col_values(3)  # 第三列为iOS key值

    # 创建翻译存储目录
    dir = mkdir("翻译")

    fileList = []
    tranList = []
    language = ['zh', 'hk', 'en', 'ja', 'es', 'pt', 'br', 'fr', 'de', 'ko', 'vi']
    languageRow = 4
    for lang in language:
        tranList.append(sheet.col_values(languageRow))
        fileName = lang + '.txt'
        path = dir +"/"+ fileName
        f = open(path, 'wb')
        f.truncate()
        fileList.append(f)
        languageRow += 1

    row = 0
    for key in cols:

        type = sheet.cell_type(row, 1)

        # print(type)
        if key == "":
            print("注意：key值为空")
        elif ((type == 1 or type == 0) and key != ""):
            languageIndex = 0
            for lang in language:
                value = tranList[languageIndex][row]
                # text = androidString(key,value)
                text = iosString(key,value)
                # print(text)
                fileList[languageIndex].write((text.encode("utf-8")))
                languageIndex += 1
        row += 1

    for fileHandle in fileList:
        fileHandle.close()



def writeFile(fileName, data, extension='txt'):
    f = open(fileName + '.' + extension, 'wb')
    f.truncate()
    f.write((''.join(data).encode("utf-8")))
    f.close()



def exportDocument(data):

    # name = td['class'][0]
    # bugNo = td.a['title']
    # priority = td.img['alt']
    # title = td.p.a.string
    # person = td.span.a.string
    # sprint = td.string
    # if td.div.ul:
    #     for li in td.div.ul.contents:
    #         if li.name == 'li':
    #             label = li.a['title']

    workbook = xlwt.Workbook()
    sheet = workbook.add_sheet('test', cell_overwrite_ok=True)

    soup = BeautifulSoup(data, 'html.parser')
    txtlist = soup.find('tbody').children
    # txts = []

    row = 0     # 行数
    for cols in txtlist:
        # 找出其中一行
        if cols.name == 'tr':
            # content = []
            row = row + 1
            if row == 1:
                continue   # 排除掉 ios key 第一行
            col = 0     # 列数
            for td in cols.contents:
                if td.name == 'td':     # 找出其中一列
                    col = col + 1  # 列数加 1
                    if td.string:
                        value = td.string.strip()  # 移除字符串头尾指定的字符（默认为空格或换行符）或字符序列 注意：该方法只能删除开头或是结尾的字符，不能删除中间部分的字符
                        # if value == "ios key":
                        #     row = 0     # 如果是第一行标题栏，则排除掉，不写入excel
                        #     break
                        sheet.write(row, col, value)
                        # content.append(value)
                        # print("row={} col={} value={}".format(row, col, value)) # 打印每一列
                    else:
                        sheet.write(row, col, td.text.strip())
                        # print("row={} col={} 数据异常".format(row, col))
                        # txts.append(content)
                else:
                    print("td.name ={} 数据异常".format(td.name))

    excel = 'test3.xls'
    workbook.save(excel)
    read_excel(excel)


def loginConfluence(account, password):

    print("开始模拟登陆Confluence")

    loginUrl = "http://wiki.orvibo.com:8190/dologin.action"
    translateUrl = "http://wiki.orvibo.com:8190/pages/viewpage.action?pageId=69108634"#"http://wiki.orvibo.com:8190/display/DOC/v3.9"

    userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36"

    postData = {
        "os_username": account,
        "os_password": password,
        "login": "登录",
        "os_destination": translateUrl # 完整网址或者不带域名也可以 "/pages/viewpage.action?pageId=47251585"
    }


    header = {
        "Referer": loginUrl,
        'User-Agent': userAgent,
    }

    # session代表某一次连接
    confluenceSession = requests.session()

    # 使用session直接post请求，获取响应内容
    resp = confluenceSession.post(loginUrl, data=postData, headers=header)

    # 登录成功之后，也可以直接用get方法获取数据
    # resp = confluenceSession.get(translateUrl, headers=header,allow_redirects=False)

    # print("post登录请求222:\n")

    # 导出翻译内容
    exportDocument(resp.text)



if __name__ == "__main__":
    # 从返回结果来看，有登录成功
    loginConfluence("wuliquan", "wjwlqyjira")
